import { createApp, toRaw } from 'vue'
import router from './router'
import { createPinia, PiniaPluginContext, PiniaPlugin } from 'pinia'
import Vant from 'vant'
import 'vant/lib/index.css'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'

// 数据存储本地
const setStorage = (key: string, value: any) => {
  sessionStorage.setItem(key, JSON.stringify(value))
}
// 获取本地数据
const getStorage = (key: string) => {
  const data = sessionStorage.getItem(key)
  return data ? JSON.parse(data) : {};
}

const piniaPlugin = (context: PiniaPluginContext) => {
  const { store } = context;
  // $subscribe state值发生变化时会执行传入的回调
  store.$subscribe(() => {
      // 每次修改值的时候更新localStorage数据
      setStorage(`pinia-${store.$id}`, toRaw(store.$state))
  })
  // 每次构建项目的时候从本地存储取值
  const data = getStorage(`pinia-${store.$id}`)
  return {
      ...data
  }
}
const store = createPinia()
store.use(piniaPlugin)
const app = createApp(App)

app.use(router).use(store).use(Vant).use(ElementPlus).mount('#app')

